import FileSaver from 'file-saver'
import * as XLSX from 'xlsx';

// 导出表格
const exportTable = (tableData, tableName) => {

    let wopts = {
        bookType: 'xlsx',
        bookSST: true,
        type: 'binary'
    };

    let workBook = {
        SheetNames: ['Sheet1'],
        Sheets: {},
        Props: {}
    };

    workBook.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(tableData);

    FileSaver.saveAs(new Blob([changeData(XLSX.write(workBook, wopts))], { type: 'application/octet-stream' }), `${tableName}.xlsx`)
    return table_write
}

const changeData = (s) => {

    //如果存在ArrayBuffer对象(es6) 最好采用该对象
    if (typeof ArrayBuffer !== 'undefined') {

        //1、创建一个字节长度为s.length的内存区域
        var buf = new ArrayBuffer(s.length);

        //2、创建一个指向buf的Unit8视图，开始于字节0，直到缓冲区的末尾
        var view = new Uint8Array(buf);

        //3、返回指定位置的字符的Unicode编码
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;

    } else {
        var buf = new Array(s.length);
        for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
}

export { exportTable }